//
//  ViewController.m
//  CoreData-Demo
//
//  Created by 赵国腾 on 2020/4/20.
//  Copyright © 2020 gaven. All rights reserved.
//

#import "TodoViewController.h"
#import <CoreData/CoreData.h>
#import "Item.h"
#import "TodoCell.h"
#import "Todo.h"

@class Item;

@interface TodoViewController () <UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property(nonatomic, strong) NSArray<Todo *> *dataList;
@property(nonatomic, strong) IBOutlet UITableView *tableView;

@end

@implementation TodoViewController

- (NSManagedObjectContext *)managedObjectContext {
    if (!_managedObjectContext) {
        
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        
        NSString *modeldPath = [NSBundle.mainBundle pathForResource:@"CoreData_Demo" ofType:@"momd"];
        NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modeldPath]];
        
        NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
        
        NSError *error = nil;
        
        NSString *sqliteDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
        
        NSURL *todoUrl = [[NSURL fileURLWithPath:sqliteDir] URLByAppendingPathComponent:@"todo.sqlite"];
        
        [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                 configuration:nil
                                                           URL:todoUrl
                                                       options:nil
                                                         error:&error];
        _managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator;
    }
    return _managedObjectContext;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
    [self loadData];
}

- (void)setupView {
    
    [self.tableView endEditing:YES];
}

- (void)loadData {
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName: Todo.entityName];
//    fetchRequest.predicate = [NSPredicate predicateWithFormat:@""];
    
    NSError *error = nil;
    NSArray<Todo *> *res = [self.managedObjectContext executeFetchRequest:fetchRequest error: &error];
    
    if (error) {
        NSLog(@"executeFetchRequest error = %@", error);
    }
    
    self.dataList = res;
    [self.tableView reloadData];
}

- (void)addData {
    
    NSEntityDescription *entity =[NSEntityDescription entityForName:Todo.entityName inManagedObjectContext:self.managedObjectContext];
    
    Todo *todo = [[Todo alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
    todo.content = @"今天学会使用CoreData";
    todo.date = [NSDate date];
    
    NSError *error = nil;
    BOOL isSave = [self.managedObjectContext save:&error];
    if (error) {
        NSLog(@"save isSave = %d error = %@", isSave, error);
    }
    
    [NSUserDefaults.standardUserDefaults setValue:@(YES) forKey:@"test"];
}

- (void)removeData {
    
}

- (IBAction)addAction {
    [self addData];
    NSLog(@"coredata数据变化 hasChanges = %d", self.managedObjectContext.hasChanges);
}

- (IBAction)refreshAction {
    [self loadData];
}

- (IBAction)modifyAction {
    
    Todo *todo = self.dataList.firstObject;
    todo.content = @"更新一下试试";
    [self.managedObjectContext save: nil];
    
    [self.tableView reloadData];
}

- (IBAction)clearAction {
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName: Todo.entityName];
    NSArray<Todo *> *res = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    
    for (Todo *t in res) {
        [self.managedObjectContext deleteObject:t];
    }
    
    [self.managedObjectContext save:nil];
    
    [self loadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TodoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TodoCell" forIndexPath:indexPath];
    cell.model = self.dataList[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Todo *model = self.dataList[indexPath.row];
        [self.managedObjectContext deleteObject:model];
        [self.managedObjectContext save:nil];
        [self loadData];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"######## start");
    for (NSInteger i = 0; i < 10; i++) {
     NSNumber *v = [NSUserDefaults.standardUserDefaults valueForKey:@"test"];
    }
    NSLog(@"######## end v = ");
    
    NSLog(@"######## start");
    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:Todo.entityName];
    fetch.predicate = [NSPredicate predicateWithFormat:@"SELF.content == '更新一下试试'"];
    for (NSInteger i = 0; i < 10; i++) {
        NSArray<Todo *> *res = [self.managedObjectContext executeFetchRequest:fetch error:nil];
    }
    NSLog(@"######## end r = ");
    
//    CFAbsoluteTimeGetCurrent()
    
}

//- (void)test {
//    self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
//
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"CoreData_Demo" withExtension:@"momd"];
//
//    // coredata 数据
//    NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
//
//    // 数据存储层
//    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
//
//    // 数据存储位置
//    NSString *sqliteDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
//    NSURL *sqliteUrl = [[NSURL fileURLWithPath:sqliteDir] URLByAppendingPathComponent:@"gaven.sqlite"];
//
//    NSError *error = nil;
//    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
//                                             configuration:nil
//                                                       URL:sqliteUrl
//                                                   options:nil
//                                                     error:&error];
//
//    if (error) {
//        NSLog(@"addPersistentStoreWithType: error = %@", error);
//    }
//
//    self.managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator;
//
//    // 增
//    for (NSInteger i = 0; i < 100; i++) {
//
//        NSString *title = [NSString stringWithFormat:@"item_title_%ld", i];
//        [Item insertItemWithTitle:title
//                            order:i
//                           parent:nil
//           inManagedObjectContext:self.managedObjectContext];
//    }
//
//    BOOL isSave = [self.managedObjectContext save:&error];
//    NSLog(@"isSave = %d", isSave);
//
//    if (error) {
//        NSLog(@"managedObjectContext save:&error = %@", error);
//    }
//
//    // 类似：SQL查询语句
//    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:Item.entityName];
//
//    NSArray *res = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//
//    if (error) {
//        NSLog(@"executeFetchRequest: error = %@", error);
//    }
//
//    NSLog(@"查询结果：");
//    for (Item *v in res) {
//        NSLog(@"title = %@", v.title);
//    }
//}

@end
